//
//  NetworkManager.m
//  BBProject
//
//  Created by Mxionlly on 16/5/20.
//  Copyright © 2016年 Mxionlly. All rights reserved.
//

#import "NetworkManager.h"
#import "AFNetworkActivityIndicatorManager.h"
#import "URLHeader.h"

static NetworkManager *sg_manager = nil;


@interface NetworkManager ()

@end


@implementation NetworkManager

+ (instancetype)sharedManager
{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        //开启转圈圈
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        
        sg_manager = [[NetworkManager alloc] initWithBaseURL:[NSURL URLWithString:YBaseURLString]];

        //超时时间
        sg_manager.requestSerializer.timeoutInterval = 30.f;
        
        // 让AFN支持text/html类型
        sg_manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", @"text/plain",@"application/atom+xml",@"application/xml",@"text/xml",@"application/octet-stream",@"multipart/mixed",@"multipart/form-data", nil];
        
    });

    return sg_manager;
}



#pragma mark - 网络请求访问的基方法
- (NSURLSessionDataTask *)baseWithUrl:(NSString *)urlString
                           parameters:(NSDictionary *)parameters
                          requestType:(YBMNetworkRequestType )requestType
                            IsLoading:(BOOL )isload
                              success:(success)success
                             failture:(failture)failture
{
    if (requestType == YBMNetworkRequestTypePost) {
        return  [self POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
                 {
                     //if (isload)
                     //错误提示
                     BOOL isSuccess = [responseObject[@"statusCode"] integerValue] == 200 ? YES : NO;

                     if(success){
                         success(task,responseObject,isSuccess);
                     }
                     
                 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     if(failture){
                         failture (error);

                     }
                 }];
    }else{
        return [self GET:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

            //错误提示
            BOOL isSuccess = [responseObject[@"statusCode"] integerValue] == 200 ? YES : NO;
            
            if(success){
                success(task,responseObject,isSuccess);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if(failture){
                failture (error);

            }
        }];
    }
}

- (NSURLSessionDataTask *)uploadWithUrl:(NSString *)urlString
                             parameters:(NSDictionary *)parameters
                                  image:(UIImage *)image
                                 imgKey:(NSString *)imgKey
                                success:(success)success
                               failture:(failture)failture
{
    NSDictionary *imagesDict = [NSDictionary dictionaryWithObject:image forKey:imgKey];
    
    return [self uploadWithUrl:urlString parameters:parameters imagesDict:imagesDict success:success failture:failture];
}

- (NSURLSessionDataTask *)uploadWithUrl:(NSString *)urlString
                             parameters:(NSDictionary *)parameters
                             imagesDict:(NSDictionary *)imagesDict
                                success:(success)success
                               failture:(failture)failture
{
    return
    [self POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         NSArray *imageKeys = [imagesDict allKeys];
         for (NSInteger i= 0; i<imageKeys.count; i++) {
             id obj = [imagesDict objectForKey:imageKeys[i]];
             
             if([obj isKindOfClass:[NSArray class]])
             {
                 NSArray *picArr = (NSArray *)obj;
                 for (int i= 0; i< picArr.count; i++) {
                     
                     [formData appendPartWithFileData:UIImagePNGRepresentation(picArr[i]) name:imageKeys[0] fileName:[NSString stringWithFormat:@"%d.jpg",i] mimeType:@"multipart/form-data"];
                 }
             }
             if([obj isKindOfClass:[UIImage class]])
             {
                 UIImage *image = (UIImage *)obj;
                 [formData appendPartWithFileData:UIImagePNGRepresentation(image)
                                             name:imageKeys[0]
                                         fileName:[NSString stringWithFormat:@"%@.png",imageKeys[0]] mimeType:@"multipart/form-data"]; //application/stream 
             }
         }
         
     } progress:^(NSProgress * _Nonnull uploadProgress) {
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

         if(success){
             success(task,responseObject,YES);
         }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         if(failture){
             failture (error);
            
         }
     }];
}
@end
